package com.ruoyi.his.service.impl;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.his.domain.HisNurse;
import com.ruoyi.his.domain.OdsDoctorData;
import com.ruoyi.his.domain.OdsHospitalAll;
import com.ruoyi.his.domain.vo.OdsDoctorAllVo;
import com.ruoyi.his.domain.vo.OdsDoctorAllVo2;
import com.ruoyi.his.domain.vo.OdsHospitalAllVo;
import com.ruoyi.his.domain.vo.OdsListDoctorAllVO;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.his.mapper.OdsDoctorAllMapper;
import com.ruoyi.his.domain.OdsDoctorAll;
import com.ruoyi.his.service.IOdsDoctorAllService;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author Alan
 * @date 2024-03-22
 */
@Service
public class OdsDoctorAllServiceImpl implements IOdsDoctorAllService
{
    @Autowired
    private SysDictDataMapper dictDataMapper;
    @Autowired
    private OdsDoctorAllMapper odsDoctorAllMapper;
    @Autowired
    private ISysUserService iUserService;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public OdsDoctorAll selectOdsDoctorAllById(Long id)
    {
        return odsDoctorAllMapper.selectOdsDoctorAllById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param odsDoctorAll 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<OdsDoctorAll> selectOdsDoctorAllList(OdsDoctorAll odsDoctorAll)
    {
        return odsDoctorAllMapper.selectOdsDoctorAllList(odsDoctorAll);
    }
    @Override
    public List<OdsDoctorAll> selectDocTowlist(OdsDoctorAll odsDoctorAll)
    {
        ArrayList<OdsDoctorAll> doc = new ArrayList<>();
        if (StringUtils.isNotEmpty(odsDoctorAll.getRegisterNumber())) {
            List<OdsDoctorAll> odsList = odsDoctorAllMapper.selectByReg(odsDoctorAll.getRegisterNumber());
            for (OdsDoctorAll odsDoctor : odsList) {
                if (!doc.contains(odsDoctor)) {
                    doc.add(odsDoctor);
                }
            }
        }
        if (StringUtils.isNotEmpty(odsDoctorAll.getHospitalId()) && StringUtils.isNotEmpty(odsDoctorAll.getSignature())) {
            List<OdsDoctorAll> odsList = odsDoctorAllMapper.selectBySigAndHos(odsDoctorAll.getSignature(), odsDoctorAll.getHospitalId());
            for (OdsDoctorAll odsDoctor : odsList) {
                if (!doc.contains(odsDoctor)) {
                    doc.add(odsDoctor);
                }
            }
        }
        return doc;
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param odsDoctorAll 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertOdsDoctorAll(OdsDoctorAll odsDoctorAll)
    {
        return odsDoctorAllMapper.insertOdsDoctorAll(odsDoctorAll);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param odsDoctorAll 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateOdsDoctorAll(OdsDoctorAll odsDoctorAll)
    {
        odsDoctorAll.setUpdateTime(DateUtils.getNowDate());
        return odsDoctorAllMapper.updateOdsDoctorAll(odsDoctorAll);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteOdsDoctorAllByIds(Long[] ids)
    {
        return odsDoctorAllMapper.deleteOdsDoctorAllByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteOdsDoctorAllById(Long id)
    {
        return odsDoctorAllMapper.deleteOdsDoctorAllById(id);
    }

    public List<OdsDoctorAll> makeList(List<OdsDoctorAll> list,String signature){
        List<OdsDoctorAll> result = new ArrayList<>();
        for(OdsDoctorAll item:list){
            if(StringUtils.isNotEmpty(item.getDoctorCode()) && StringUtils.isNotEmpty(item.getName())) {
                item.setSignature(signature);
                item.setUpdateTime(new Date());
                result.add(item);
            }
        }
        return result;
    }

    /**
     * 对外的接口
     * @param vo
     * @return
     */
    @Override
    public AjaxResult insterDoc(OdsListDoctorAllVO vo) {

        SysDictData pa = new SysDictData();
        //查询是否有签名
        pa.setDictType("his");
        pa.setStatus("0");
        pa.setDictValue(vo.getSignature());
        int count = dictDataMapper.selectByCount(pa);
        if (count==0)
        {
            return AjaxResult.error("没有签名未授权访问！");
        }
        //设置签名
        List<OdsDoctorAll> list = makeList(vo.getData(),vo.getSignature());
        if(list.size()==0){
            return AjaxResult.error("请传入必填参数！");
        }
        //批量插入
        odsDoctorAllMapper.InsertOfList(list);
        //批量更新按身份证号
        odsDoctorAllMapper.updateOfListIdCard(list);
        //批量更新按执业号
        odsDoctorAllMapper.updateOfListIdLicence(list);
        //批量更新按编号
        odsDoctorAllMapper.updateOfListDcode(list);
        //批量删除按编号只保留最早一条
        odsDoctorAllMapper.deleteKeepOneByIdCard();
        odsDoctorAllMapper.deleteKeepOneBylicence();
        odsDoctorAllMapper.deleteKeepOneByDid();
        return AjaxResult.success();
    }

    public String registerDoctorRule(OdsDoctorAll odsDoctorAll){
        SysDictData param = new SysDictData();
        //查询是否有签名
        param.setDictType("his");
        param.setStatus("0");
        param.setDictValue(odsDoctorAll.getSignature());
        int count = dictDataMapper.selectByCount(param);
        if (count==0)
        {
            return "没有签名未授权访问！";
        }
        if (StringUtils.isEmpty(odsDoctorAll.getRegionCode())) {
            return "请选择辖区！";
        }
        if (StringUtils.isEmpty(odsDoctorAll.getHospitalId())) {
            return "请选择机构！";
        }
        if (StringUtils.isEmpty(odsDoctorAll.getName())) {
            return "医师姓名不能为空！";
        }
        if (StringUtils.isEmpty(odsDoctorAll.getMobile())) {
            return "手机号码不能为空！";
        }
        if (StringUtils.isEmpty(odsDoctorAll.getIdCard())) {
            return "医师身份证号不能为空！";
        }
        if (StringUtils.isEmpty(odsDoctorAll.getSex())) {
            return "请选择医师性别！";
        }
        if (StringUtils.isEmpty(odsDoctorAll.getBirthday())) {
            return "请选择出生日期！";
        }
        if (StringUtils.isEmpty(odsDoctorAll.getAntecedent())) {
            return "医师学历不能为空！";
        }
        if (StringUtils.isEmpty(odsDoctorAll.getSpecialty())) {
            return "医师院校和专业不能为空！";
        }
        if (StringUtils.isEmpty(odsDoctorAll.getDoctorLicence())) {
            return "医师执业证书不能为空！";
        }
        if (StringUtils.isEmpty(odsDoctorAll.getQualification())) {
            return "医师资格证书不能为空！";
        }

        if (odsDoctorAll.getAntibiosisAuthority()==null) {
            return "请选择医师抗菌处方权！";
        }
        if (odsDoctorAll.getAnestheticAuthority()==null) {
            return "请选择医师有无精麻处方权！";
        }
        if (odsDoctorAll.getAntibiosisAuthority()==null) {
            return "请选择医师抗菌处方权！";
        }
        if (odsDoctorAll.getAntibiosisAuthority()==null) {
            return "请选择医师抗菌处方权！";
        }
        if (StringUtils.isEmpty(odsDoctorAll.getUsername())) {
            return "用户名不能为空！";
        }
        if (StringUtils.isEmpty(odsDoctorAll.getPassword())) {
            return "密码不能为空！";
        }
        return null;
    }

    /**
     * 医生注册的业务 选择医师的时候
     * @param odsDoctorAll
     * @return
     */
    @Override
    public AjaxResult registerDoctorByLicenceSelect(OdsDoctorAll odsDoctorAll) {
        String msg = registerDoctorRule(odsDoctorAll);
        if(msg!=null){
            return AjaxResult.error(msg);
        }

        //通过用户名判断 判断用户是否存在
        String s = iUserService.checkUserNameUnique(odsDoctorAll.getUsername());
        if(!(s.equals(UserConstants.UNIQUE))){
            return AjaxResult.error("用户名已经被注册了！");
        }
        //通过执业证号判断用户是否存在
        if((iUserService.selectUserByDocLis(odsDoctorAll.getDoctorLicence())) != null){
            return AjaxResult.error("医师已经被注册了！");
        }


        //密码加密
        String password = SecurityUtils.encryptPassword(odsDoctorAll.getPassword());
        SysUser sysUser = new SysUser();
        sysUser.setUserName(odsDoctorAll.getUsername());
        sysUser.setPassword(password);
        sysUser.setUserType("8");
        sysUser.setDoctorCode(odsDoctorAll.getDoctorCode());
        sysUser.setDoctorLicence(odsDoctorAll.getDoctorLicence());
        sysUser.setUpdateTime(new Date());
        odsDoctorAll.setIntonum(1);
        //添加个用户
        int j = iUserService.insertUser(sysUser);
        //更新当前临时注册的字段

        if(j>0) {
            List<OdsDoctorAll> list = new ArrayList<>();
            list.add(odsDoctorAll);
            //批量插入
            odsDoctorAllMapper.InsertOfList(list);
            //批量更新按身份证号
            odsDoctorAllMapper.updateOfListIdCard(list);
            //批量更新按执业号
            odsDoctorAllMapper.updateOfListIdLicence(list);
            //批量更新按编号
            odsDoctorAllMapper.updateOfListDcode(list);
            //批量删除按编号只保留最早一条
            odsDoctorAllMapper.deleteKeepOneByIdCard();
            odsDoctorAllMapper.deleteKeepOneBylicence();
            odsDoctorAllMapper.deleteKeepOneByDid();
        }
        return AjaxResult.success();

    }

//    /**
//     * 对外的接口
//     * @param vo
//     * @return
//     */
//    @Override
//    public AjaxResult insterDoc(OdsListDoctorAllVO vo) {
//
//        SysDictData pa = new SysDictData();
//        //查询是否有签名
//        pa.setDictType("his");
//        pa.setStatus("0");
//        pa.setDictValue(vo.getSignature());
//        int count = dictDataMapper.selectByCount(pa);
//        if (count==0)
//        {
//            return AjaxResult.error("没有签名未授权访问！");
//        }
//        HashMap<String,OdsDoctorAll> map = makeMap(vo.getData());
//        OdsDoctorAll param = new OdsDoctorAll();
//        for(Map.Entry<String,OdsDoctorAll> item :map.entrySet()){
//            param.setDoctorLicence(null);
//            param.setDoctorCode(null);
//            param.setIdCard(null);
//            OdsDoctorAll odsDoctorAll =  item.getValue();
//            odsDoctorAll.setIntonum(1);
//            odsDoctorAll.setSignature(vo.getSignature());
//            List<OdsDoctorAll> result1 = null;
//            List<OdsDoctorAll> result2 = null;
//            List<OdsDoctorAll> result3 = null;
//            //根据执业证号号去更新dcode
//            if(StringUtils.isNotEmpty(odsDoctorAll.getDoctorLicence())){
//                param.setDoctorLicence(odsDoctorAll.getDoctorLicence());
//                result1 =  odsDoctorAllMapper.selectByLicence(param);
//                for(OdsDoctorAll old:result1){
//                    if(old.getId()!=null) {
//                        odsDoctorAll.setUpdateTime(new Date());
//                        odsDoctorAll.setId(old.getId());
//                        odsDoctorAllMapper.updateOdsDoctorAll(odsDoctorAll);
//                    }
//                }
//            }
//
//            //根据身份证号号去更新dcode
//            if(StringUtils.isNotEmpty(odsDoctorAll.getIdCard())){
//                param.setIdCard(odsDoctorAll.getIdCard());
//                result2 =  odsDoctorAllMapper.selectByIdCard(param);
//                for(OdsDoctorAll old:result2){
//                    if(old.getId()!=null) {
//                        odsDoctorAll.setUpdateTime(new Date());
//                        odsDoctorAll.setId(old.getId());
//                        odsDoctorAllMapper.updateOdsDoctorAll(odsDoctorAll);
//                    }
//                }
//            }
//
//            //根据doctorcode号号去更新dcode
//            if(StringUtils.isNotEmpty(odsDoctorAll.getDoctorCode())){
//                param.setDoctorCode(odsDoctorAll.getDoctorCode());
//                result3 =  odsDoctorAllMapper.selectOdsDoctorAllList(param);
//                for(OdsDoctorAll old:result3){
//                    if(old.getId()!=null) {
//                        odsDoctorAll.setUpdateTime(new Date());
//                        odsDoctorAll.setId(old.getId());
//                        odsDoctorAllMapper.updateOdsDoctorAll(odsDoctorAll);
//                        map.put(odsDoctorAll.getDoctorCode(),null);
//                    }
//                }
//            }
//        }
//
//
//        //通过签名和doctorcode判断医师是否存在
//        for(Map.Entry<String,OdsDoctorAll> item :map.entrySet()){
//            OdsDoctorAll odsDoctorAll =  item.getValue();
//            if(odsDoctorAll!=null) {
//                odsDoctorAll.setCreateTime(new Date());
//                odsDoctorAll.setId(null);
//                //没有用户就插入
//                odsDoctorAllMapper.insertOdsDoctorAll(odsDoctorAll);
//            }
//        }
//        return AjaxResult.success();
//    }




//    /**
//     * 医生注册的业务 选择医师的时候
//     * @param odsDoctorAll
//     * @return
//     */
//    @Override
//    public AjaxResult registerDoctorByLicenceSelect(OdsDoctorAll odsDoctorAll) {
//        String msg = registerDoctorRule(odsDoctorAll);
//        if(msg!=null){
//            return AjaxResult.error(msg);
//        }
//
//        if (StringUtils.isEmpty(odsDoctorAll.getDoctorCode())){
//            return AjaxResult.error("请选择医生！");
//        }
//        OdsDoctorAll param = new OdsDoctorAll();
//        //查询是否有签名
//        param.setSignature(odsDoctorAll.getSignature());
//        //查询在这个签名下his系统是否有这个医生
//        param.setDoctorCode(odsDoctorAll.getDoctorCode());
//        List<OdsDoctorAll> result2 =  odsDoctorAllMapper.selectOdsDoctorAllList(param);
//        //通过用户名判断 判断用户是否存在
//        String s = iUserService.checkUserNameUnique(odsDoctorAll.getUsername());
//        if(!(s.equals(UserConstants.UNIQUE))){
//            return AjaxResult.error("用户名已经被注册了！");
//        }
//        //通过执业证号判断用户是否存在
//        if((iUserService.selectUserByDocLis(odsDoctorAll.getDoctorLicence())) != null){
//            return AjaxResult.error("医师已经被注册了！");
//        }
//
//
//        //密码加密
//        String password = SecurityUtils.encryptPassword(odsDoctorAll.getPassword());
//        SysUser sysUser = new SysUser();
//        sysUser.setUserName(odsDoctorAll.getUsername());
//        sysUser.setPassword(password);
//        sysUser.setUserType("8");
//        sysUser.setDoctorLicence(odsDoctorAll.getDoctorLicence());
//        sysUser.setUpdateTime(new Date());
//        odsDoctorAll.setIntonum(1);
//        //添加个用户
//        int j = iUserService.insertUser(sysUser);
//        //更新当前临时注册的字段
//        int i = 0;
//        if(result2==null||result2.size()==0){
//            //没有在his系统中的医生作插入操作
//            i = odsDoctorAllMapper.insertOdsDoctorAll(odsDoctorAll);
//        }else {
//            //在his系统中的医生作更新操作
//            for(OdsDoctorAll item : result2){
//                if(item.getId()!=null){
//                    odsDoctorAll.setId(item.getId());
//                    odsDoctorAllMapper.updateOdsDoctorAll(odsDoctorAll);
//                }
//            }
//        }
//        return AjaxResult.success();
//
//    }

    /**
     * 医生注册的业务 未选择医师的时候
     * @param odsDoctorAll
     * @return
     */
    @Override
    public AjaxResult registerDoctorByLicenceUnSelect(OdsDoctorAll odsDoctorAll) {
        String msg = registerDoctorRule(odsDoctorAll);
        if(msg!=null){
            return AjaxResult.error(msg);
        }

        if (StringUtils.isEmpty(odsDoctorAll.getDoctorCode())){
            return AjaxResult.error("请选择医生！");
        }
        OdsDoctorAll param = new OdsDoctorAll();
        //查询是否有签名
        param.setSignature(odsDoctorAll.getSignature());
        //查询在这个签名下his系统是否有这个医生
        param.setIdCard(odsDoctorAll.getIdCard());
        List<OdsDoctorAll> result2 =  odsDoctorAllMapper.selectOdsDoctorAllList(param);
        //通过用户名判断 判断用户是否存在
        String s = iUserService.checkUserNameUnique(odsDoctorAll.getUsername());
        if(!(s.equals(UserConstants.UNIQUE))){
            return AjaxResult.error("用户名已经被注册了！");
        }
        //通过执业证号判断用户是否存在
        if((iUserService.selectUserByDocLis(odsDoctorAll.getDoctorLicence())) != null){
            return AjaxResult.error("医师已经被注册了！");
        }


        //密码加密
        String password = SecurityUtils.encryptPassword(odsDoctorAll.getPassword());
        SysUser sysUser = new SysUser();
        sysUser.setUserName(odsDoctorAll.getUsername());
        sysUser.setPassword(password);
        sysUser.setUserType("8");
        sysUser.setDoctorLicence(odsDoctorAll.getDoctorLicence());
        sysUser.setUpdateTime(new Date());
        odsDoctorAll.setIntonum(1);
        //添加个用户
        int j = iUserService.insertUser(sysUser);
        //更新当前临时注册的字段
        int i = 0;
        if(result2==null||result2.size()==0){
            //没有在his系统中的医生作插入操作
            i = odsDoctorAllMapper.insertOdsDoctorAll(odsDoctorAll);
        }else {
            //在his系统中的医生作更新操作
            for(OdsDoctorAll item : result2){
                if(item.getId()!=null){
                    odsDoctorAll.setId(item.getId());
                    odsDoctorAllMapper.updateOdsDoctorAll(odsDoctorAll);
                }
            }
        }
        return AjaxResult.success();

    }

    @Override
    public String importData2(List<OdsDoctorAllVo2> userList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入机构数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (OdsDoctorAllVo2 user : userList)
        {
            try
            {
                OdsDoctorAll odsHospitalAll= new OdsDoctorAll();
                BeanUtils.copyProperties(user,odsHospitalAll);
                this.odsDoctorAllMapper.insertOdsDoctorAll(odsHospitalAll);
                successNum++;
                successMsg.append("<br/>" + successNum + "、姓名 " + user.getName() + " 导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、姓名 " + user.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public String importData(List<OdsDoctorAllVo> userList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入机构数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (OdsDoctorAllVo user : userList)
        {
            try
            {
                if(org.apache.commons.lang3.StringUtils.isBlank(user.getDoctorLicence())){
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、执业证书编码 " + user.getDoctorLicence() + " 导入失败：";
                    failureMsg.append(msg );
                    break;
                }
                OdsDoctorAll u = odsDoctorAllMapper.selectBySignatureIsNotNull(user.getDoctorLicence());
                OdsDoctorAll odsHospitalAll= new OdsDoctorAll();
                BeanUtils.copyProperties(user,odsHospitalAll);
                if (StringUtils.isNull(u))
                {
                    this.odsDoctorAllMapper.insertOdsDoctorAll(odsHospitalAll);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、执业证书编码 " + user.getDoctorLicence() + " 导入成功");
                }
                else
                {
                    odsHospitalAll.setId(u.getId());
                    this.updateOdsDoctorAll(odsHospitalAll);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、执业证书编码 " + user.getDoctorLicence() + " 更新成功");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、执业证书编码 " + user.getDoctorLicence() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 获取医师的业务
     * @param signature
     * @return
     */
    @Override
    public List<OdsDoctorAll> selectOdsDocListBySig(String signature) {
        return odsDoctorAllMapper.selectOdsDocListBySig(signature);

    }

    @Override
    public Integer checkSameName(String signature) {
        OdsDoctorAll all = new OdsDoctorAll();
        all.setSignature(signature);
        List<OdsDoctorAll> list1 = odsDoctorAllMapper.selectOdsDoctorAllList(all);
        if(list1==null || list1.size()==0){
            return 1;
        }else {
            List<OdsDoctorAll> list = odsDoctorAllMapper.checkSameName(signature);
            if(list==null || list.size()==0){
                return 0;
            }else{
                return 1;
            }
        }
    }
}
